import { HttpException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/database/entities/user';
import { RedisService } from 'src/database/redis';
import { ExpTime } from 'src/const';
@Injectable()
export class UserService {
  constructor(
    private jwtService: JwtService,
    private redisService: RedisService,
  ) {}
  async createUser(user: User) {
    const findUser = await User.findOneBy({
      account: user.account,
      password: user.password,
    });

    if (findUser) {
      throw new HttpException('用户已存在', 400);
    }

    await User.save(user);
  }

  static CreateTokenKey(id: string | number) {
    return `TOKEN_${id}`;
  }

  async loginUser(user: User) {
    const findUser = await User.findOneBy({
      account: user.account,
      password: user.password,
    });
    if (!findUser) {
      throw new HttpException(
        {
          message: '账号或密码错误',
        },
        400,
      );
    }
    const token = this.jwtService.sign({ id: findUser.id });
    const TokenKey = UserService.CreateTokenKey(findUser.id);
    await this.redisService.redis.hset(TokenKey, {
      id: findUser.id,
      token,
    });
    await this.redisService.redis.expire(TokenKey, ExpTime);
    return token;
  }

  async logout(userId: number) {
    await this.redisService.redis.del(UserService.CreateTokenKey(userId));
  }
}
